package com.lancoo.cvas.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.Pair;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.cvas.entity.*;
import com.lancoo.cvas.mapper.TeacherMapper;
import com.lancoo.cvas.mapper.TeachingClassMapper;
import com.lancoo.cvas.mapper.TeachingClassTeacherMapper;
import com.lancoo.cvas.pojo.common.CollComparatorUtil;
import com.lancoo.cvas.pojo.common.Deleted;
import com.lancoo.cvas.pojo.common.ScheduleState;
import com.lancoo.cvas.pojo.response.basicPlatform.BaseTeacher;
import com.lancoo.cvas.pojo.vo.TeacherGroup;
import com.lancoo.cvas.pojo.vo.TeachingClassCourseDto;
import com.lancoo.cvas.service.TaskInfoService;
import com.lancoo.cvas.service.TeacherService;
import com.lancoo.cvas.service.TeachingClassTeacherService;
import com.lancoo.cvas.util.RedisUtil;
import com.sun.org.apache.bcel.internal.generic.LRETURN;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.Delayed;
import java.util.stream.Collectors;


@Service("teacherService")
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {


    @Resource
    private CollComparatorUtil collComparatorUtil;

    @Resource
    private TeachingClassTeacherMapper teachingClassTeacherMapper;
    @Resource
    private TeachingClassTeacherService teachingClassTeacherService;

    @Resource
    private TeacherMapper teacherMapper;

    @Resource
    private TeacherService teacherService;
    @Resource
    private RedisUtil redisUtil;


    @Resource
    private TeachingClassMapper teachingClassMapper;
    @Resource
    private TaskInfoService taskInfoService;

    @Override
    public void syncBaseTeachers(Integer taskId, List<BaseTeacher> baseTeachers, String schoolId, String term) {
        List<Teacher> syncTeacherList = new ArrayList<>();


        for (BaseTeacher baseTeacher : baseTeachers) {
            syncTeacherList.add(baseTeacher.toTeacher(taskId, schoolId, term));
        }




        if(CollUtil.isNotEmpty(syncTeacherList)){
            teacherMapper.addBatch(syncTeacherList);
        }


        redisUtil.del("cvas:com.lancoo.cvas.mapper.TeacherMapper");


    }

    @Override
    public List<Teacher> getTeacherByTeachingClassIds(List<Long> teachingClassIds) {
        if (CollUtil.isEmpty(teachingClassIds)) {
            return new ArrayList<>();
        }
        //加了type
        List<Teacher> teacherList = teachingClassTeacherMapper.getTeacherByTeachingClassIds(teachingClassIds);
        return teacherList;
    }

    /**
     * 根据课题组获取全部教师
     *
     * @param schoolId
     * @param term
     * @return
     */
    @Override
    public List<TeacherGroup> getTeacherListGroup(Integer taskId, String schoolId, String term, Integer module) {
        List<TeacherGroup> teacherGroupList = new ArrayList<>();


        List<Teacher> list = this.list(new LambdaQueryWrapper<Teacher>()
                .eq(Teacher::getSchoolId, schoolId).eq(Teacher::getDeleted, Deleted.NOT.getCode())
                .eq(Teacher::getTerm, term).eq(Teacher::getIsEnable, 1));

        //排除没课的教师
        if (module == 3) {
            Page<TeachingClassCourseDto> page = new Page<>(1, -1);
            List<TeachingClassCourseDto> records = teachingClassMapper.getCourseTeachingClassForArrange(page, taskId, null, null, null, null).getRecords();
            records = records.stream().filter(o -> StrUtil.isEmpty(o.getUniqueShiftSign())).collect(Collectors.toList());
            if (CollUtil.isEmpty(records)){
                list.clear();
            }else {
                List<Long> allTeacherIds = teachingClassTeacherMapper.getTeacherHasClassByTaskId(taskId,records,Deleted.NOT.getCode());
                list = list.stream().filter(o -> allTeacherIds.contains(o.getTeacherId())).collect(Collectors.toList());
            }

//            List<Long> allTeacherIds = teachingClassTeacherMapper.getTeacherHasScheduleByTaskId(taskId,Deleted.NOT.getCode());
//            list = list.stream().filter(o -> allTeacherIds.contains(o.getTeacherId())).collect(Collectors.toList());
        }

        list.stream()
                .filter(record -> record.getGroupId() == null && record.getGroupName() == null)
                .forEach(record -> {
                    record.setGroupId("000");
                    record.setGroupName("未分组教师");
                });


        if (module == 2) {
            Page<TeachingClassCourseDto> page = new Page<>(1, -1);
            List<TeachingClassCourseDto> records = teachingClassMapper.getCourseTeachingClassForArrange(page, taskId, null, null, null, null).getRecords();
            List<TeachingClassCourseDto> unRang = records.stream().filter(o -> o.getState() == ScheduleState.UNARRANGE.getCode()
                    || o.getState() == ScheduleState.CONFLICT.getCode()).collect(Collectors.toList());

            List<TeachingClassTeacher> allTeachers = new ArrayList<>();
             /*
                过滤没有课的教师
                 */
            List<Long> allTeachingClassIds = records.stream()
                    .map(TeachingClassCourseDto::getTeachingClassId)
                    .distinct().collect(Collectors.toList());
            if (CollUtil.isNotEmpty(allTeachingClassIds)){
                allTeachers = teachingClassTeacherService.lambdaQuery()
                        .in(TeachingClassTeacher::getTeachingClassId, allTeachingClassIds)
                        .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode())
                        .list();
                List<Long> allTeacherIds = allTeachers.stream().map(TeachingClassTeacher::getTeacherId).distinct()
                        .collect(Collectors.toList());
                list = list.stream().filter(o -> allTeacherIds.contains(o.getTeacherId())).collect(Collectors.toList());
            }else {
                list = new ArrayList<>();
            }

            //排课状态
            if (CollUtil.isNotEmpty(unRang)) {
                /*
                List<Long> teachingClassIds = unRang.stream()
                        .map(TeachingClassCourseDto::getTeachingClassId)
                        .distinct().collect(Collectors.toList());
//                allTeachers.stream().filter()
                List<Long> teacherIds = allTeachers.stream().filter(o -> teachingClassIds.contains(o.getTeachingClassId()))
                        .map(TeachingClassTeacher::getTeacherId).collect(Collectors.toList());
//                        teachingClassTeacherService.lambdaQuery()
//                        .in(TeachingClassTeacher::getTeachingClassId, teachingClassIds)
//                        .eq(TeachingClassTeacher::getDeleted, Deleted.NOT.getCode())
//                        .list().stream().map(TeachingClassTeacher::getTeacherId).distinct()
//                        .collect(Collectors.toList());

                 */

                HashSet<Long> teacherIds = new HashSet<>();
                for (TeachingClassTeacher teacher : allTeachers) {
                    if(unRang.stream().anyMatch(o -> Objects.equals(o.getTeachingClassId(), teacher.getTeachingClassId())
                        && Objects.equals(o.getHourType(), teacher.getTeacherType()))){
                        teacherIds.add(teacher.getTeacherId());
                    }
                }


                list.forEach(o -> {
                    if (teacherIds.contains(o.getTeacherId())) {
                        o.setState(false);
                    }
                });
            }
        }

        //根据学院id 名字分组
        Map<Pair<String, String>, List<Teacher>> listMap = list.stream().collect(Collectors.groupingBy(p -> Pair.of(p.getGroupId(), p.getGroupName())));
        listMap.entrySet().forEach(o -> {
            TeacherGroup teacherGroup = new TeacherGroup();
            teacherGroup.setGroupId(o.getKey().getKey());
            teacherGroup.setGroupName(o.getKey().getValue());
            teacherGroup.setTeacherList(o.getValue());
            teacherGroup.setSum(o.getValue().size());
            if (o.getValue().stream().anyMatch(t -> !t.getState())) {
                teacherGroup.setState(false);
            }
            teacherGroupList.add(teacherGroup);
        });
        return teacherGroupList.stream().sorted(Comparator.comparing(TeacherGroup::getGroupName)).collect(Collectors.toList());
    }

    @Override
    public List<Teacher> getTeacherByKeyword(String schoolId, String term, String keyword) {
        return teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().eq(Teacher::getSchoolId, schoolId).eq(Teacher::getTerm, term)
                .and(StrUtil.isNotBlank(keyword), wrapper -> wrapper.like(Teacher::getTeacherName, keyword)
                        .or().like(Teacher::getGroupName, keyword)));
    }

    @Override
    public List<Teacher> getSubTeacherList(Integer taskId, String subId) {

        //获取拆班教师
        List<TeachingClass> teachingClassList = teachingClassMapper.selectList(new LambdaQueryWrapper<TeachingClass>()
                .eq(TeachingClass::getTaskId,taskId)
                .eq(TeachingClass::getUniqueShiftSign,subId)
                .eq(TeachingClass::getDeleted,Deleted.NOT.getCode()));
        List<Long> teachingClassIds = teachingClassList.stream().map(TeachingClass::getTeachingClassId).collect(Collectors.toList());

        List<Long> collect = new ArrayList<>();
        if(CollUtil.isNotEmpty(teachingClassIds)){
            List<TeachingClassTeacher> teachingClassTeacherList = teachingClassTeacherService.lambdaQuery()
                    .in(TeachingClassTeacher::getTeachingClassId,teachingClassIds)
                    .eq(TeachingClassTeacher::getDeleted,Deleted.NOT.getCode()).list();
            collect = teachingClassTeacherList.stream().map(TeachingClassTeacher::getTeacherId)
                    .distinct().collect(Collectors.toList());

        }

        TaskInfo taskInfo = taskInfoService.getById(taskId);

        List<Teacher> teacherList = teacherMapper.selectTeacherList(taskInfo.getSchoolId(),taskInfo.getTerm());
//        List<Teacher> teacherList = teacherMapper.selectList(new LambdaQueryWrapper<Teacher>().eq(Teacher::getSchoolId,taskInfo.getSchoolId())
//                .eq(Teacher::getTerm,taskInfo.getTerm()).eq(Teacher::getDeleted,Deleted.NOT.getCode()));
        if(CollUtil.isNotEmpty(collect)){
            List<Long> finalCollect = collect;
            teacherList = teacherList.stream().filter(p->!finalCollect.contains(p.getTeacherId())).collect(Collectors.toList());
        }

        return teacherList;
    }

    @Override
    public List<Teacher> selectTeacherList(String schoolId, String term) {
        return teacherMapper.selectTeacherList(schoolId, term);
    }
}